package com.camera2.http;


import android.content.Context;
import android.util.Log;

import com.camera2.bean.ApplicationHelper;
import com.camera2.bean.MessageBean;
import com.camera2.local.SharedPrefer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetMessage {

    private static Context context;
    private static int code;
    private static String msg;
    private static List<MessageBean> beanList;
    private static MessageBean bean;

    public static String get(Context context1) throws Exception {
        context = context1;
        String token = SharedPrefer.ReadToken(context);
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder()
                .add("params", "10")
                .build();
        Request request = new Request.Builder()
                .url(GlobalUrl.getExpertMessageUrl())
                .post(body)
                .addHeader("token",token)
                .build();

        Call call = mOkHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String result = (String) response.body().string();
            Log.i("GetMessage", "result: "+result);
            JSONObject jsonObj = new JSONObject(result);
            code = Integer.parseInt(jsonObj.getString("code"));
            msg =  jsonObj.getString("msg") ;

            String page = jsonObj.getString("page");
            JSONObject pagejsonObj = new JSONObject(page);
            String list = pagejsonObj.getString("list");

            Log.i("GetMessage", "list:  " + list);
            if (code == 0) {
                Gson gs = new Gson();
                beanList = gs.fromJson(list, new TypeToken<List<MessageBean>>() {
                }.getType());
                ((ApplicationHelper) context1.getApplicationContext()).setMessageBeanList(beanList);
                List<MessageBean> aa = ((ApplicationHelper) context1.getApplicationContext()).getMessageBeanList();
                Log.i("GetMessage", "List<ExpertBean>: " + aa);
            }
            else return msg;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }


}
